package com.example.hs.Service;

import com.example.hs.Pojo.Address;
import com.example.hs.Pojo.User;
import com.example.hs.Repository.AddressRepository;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AddressService {
    @Autowired
    private AddressRepository addressRepository;
    public List<Address> getAddressesByUserId(int userId) {
        return addressRepository.findByUserId(userId);
    }
    public Address addAddress(Address address, HttpSession session) {
        User user = (User) session.getAttribute("user");
        address.setUserId(user.getUserId());
        // 设置创建时间和更新时间为当前时间
        LocalDateTime now = LocalDateTime.now();
        address.setUpdate_time(now);
        return addressRepository.save(address);
    }
    public Address updateAddress(int addressId, Address updateAddress) {
        Address address = addressRepository.findById(addressId).orElse(null);
        address.setName(updateAddress.getName());
        address.setPhone(updateAddress.getPhone());
        address.setAddress(updateAddress.getAddress());
        // 设置更新时间为当前时间
        LocalDateTime now = LocalDateTime.now();
        address.setUpdate_time(now);
        return addressRepository.save(address);
    }
}
